package cn.zwx.business.member.service.remote;

import cn.zwx.business.member.service.annotation.ZwxReference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 *  在注入之前进行赋值
 *  @author zhangwenxue
 */
@Component
public class ReferenceInvokeProxy implements BeanPostProcessor {

    @Resource
    RemoteInvocationHandler remoteInvocationHandler;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if (declaredField.isAnnotationPresent(ZwxReference.class)){
                // 调用代理类创建代理对象
                Class<?> type = declaredField.getType();
                Object newProxyInstance = Proxy.newProxyInstance(type.getClassLoader(), new Class[]{
                        type}, remoteInvocationHandler);
                // 进行属性注入
                try {
                    declaredField.set(bean,newProxyInstance);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
